<?php
class DB
{
	var $db;
    var $write_log = false;
	function __construct($host,$user,$password,$dbname){
		$this->db = @mysql_connect($host,$user,$password);
		if (!$this->db){
			$this->write_err_log($host, mysql_error());
			// 重试
			$this->db = @mysql_connect($host,$user,$password);
			if (!$this->db){
				$this->write_err_log($host, mysql_error(), 'retry');
				return false;
			}
		}
		mysql_select_db($dbname, $this->db);
		mysql_query("set names 'utf8'");
		return true;
	}

	function closs(){
		mysql_close($this->db);
	}

	function query($sql){
		$query_result = mysql_query($sql, $this->db);
		if ($query_result === true){ // 执行 insert update replace 等的结果
			$re = true;
		}elseif($query_result === false){ // sql执行错误
			$re = false;
			$this->write_err_log('unknown!', mysql_error(), 'query');
		}else{ // 执行 select 的结果
			$re = array();
			$row = mysql_fetch_array($query_result, MYSQL_ASSOC);
			while($row){
				$re[] = $row;
				$row = mysql_fetch_array($query_result, MYSQL_ASSOC);
			}
		}
		return $re;
	}

	// 数据库错误日志
	function write_err_log($host, $info, $type='conn'){
        return true;
        if (!$this->write_log) return true;

		$time = date('Y-m-d H:i:s');
		$log_str = "HOST:{$host}\tINFO:{$info}\tTIME:{$time}\tTYPE:{$type}\n";
		$logpath = '/data0/weibo_scripts/dberrlog/' . date('Ym/');
		if (!file_exists($logpath)){
			@mkdir($logpath, 777, true);
		}
		@file_put_contents($logpath.'errlog', $log_str, FILE_APPEND);
		return true;
	}
}


// 连接xiaohei库
function db_xiaohei() {
    global $DBCONF;
	return new DB($DBCONF['XIAOHEI']['HOST'], $DBCONF['XIAOHEI']['USER'], $DBCONF['XIAOHEI']['PASSWORD'], $DBCONF['XIAOHEI']['DB']);
}

// 连接Weibo库
function db_weibo() {
    global $DBCONF;
	return new DB($DBCONF['WEIBO']['HOST'], $DBCONF['WEIBO']['USER'], $DBCONF['WEIBO']['PASSWORD'], $DBCONF['WEIBO']['DB']);
}
